package gen.background.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Map;

import gen.background.TemplateParse;
import gen.background.entity.TableObject;
import gen.background.util.JavaToClass;

public class JavaGenerate {
	private String content;
	private StringBuffer code = new StringBuffer();
	
	public String initContent(){
		String impont = "import gen.background.entity.TableObject;\n"+
						"import java.io.FileOutputStream;\n"+
						"import java.io.PrintWriter;\n"+ 
						"import gen.background.util.codingUtil;\n"+
						"import java.util.Map;\n"+
						"import java.io.File;\n"+
						"import gen.background.entity.Column;\n"+
						"import gen.background.core.TemplateToGenerate;\n";
		String str 
			= 	"public class Generator extends TemplateToGenerate {\n"+
				"	public void generate(TableObject table,File file,Map<String,String> params) throws Exception{\n"+
				"		System.out.println(\"测试\");\n"+
					
				"		PrintWriter out = null;\n"+
				"		try{\n"+
				"			FileOutputStream fos = new FileOutputStream(file);\n"+
				"			out = new PrintWriter(fos);\n"+
							
							(code==null||code.length()<=0?"":code)+
							
				"		}finally {\n"+
				"			out.close();\n"+
				"		}\n"+
				"	}\n"+
				"}\n";
		
		return impont+str;
	}
	
	public void addCode(String code){
		this.code.append("			"+code+"\n");
	}
	
	public void printParam(String param){
		this.code.append("			out.print({param});\n".replace("{param}",param));
	}
	
	public void printTemplate(String templ){
		this.code.append("			out.print(codingUtil.decode(\"{templ}\"));\n".replace("{templ}",templ));
	}
	
	public void printlnTemplate(String templ){
		this.code.append("			out.println(codingUtil.decode(\"{templ}\"));\n".replace("{templ}",templ));
	}
	
	public void execute(TableObject table,File file,Map<String,String> params) throws Exception{
		content = initContent();
		System.out.println(content);
		Map<String, byte[]> bytecode = JavaToClass.compile("Generator.java", content);
		JavaToClass.MemoryClassLoader classLoader = new JavaToClass.MemoryClassLoader(bytecode);
		Class clazz = classLoader.loadClass("Generator");
		TemplateToGenerate object = (TemplateToGenerate) clazz.newInstance();
		object.generate(table,file,params);
	}
	
	public static void main(String[] args) throws Exception{
		JavaGenerate jg = new JavaGenerate();
		File file = new TemplateParse().getFile("com/zg/background/dao/impl.xml");
		System.out.println(file.getPath());
		//System.out.println(jg.initContent());
		//jg.execute(null,file,null);
		PrintWriter pw = null;
		try{
			FileOutputStream fos = new FileOutputStream(file);
			pw = new PrintWriter(fos);
			pw.println("fewfwefj");
			pw.print("jkl");
		}finally {
			pw.close();
		}
	}
	
}